package com.wanmait.cookbook.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.wanmait.cookbook.vo.Userinfo;
import com.wanmait.cookbook.vo.Works;
import com.wanmait.cookbook.vo.WorksImages;
import com.wanmait.demo.util.DBHelper;

/*
 *作品图库表DAO
 */
public class WorksImagesDAO {
	private WorksImagesDAO() {}
	private static WorksImagesDAO worksImagesDAO = new WorksImagesDAO();
	public static WorksImagesDAO getWorksImagesDAO() {
		return worksImagesDAO;
	}
	  /**
	   *  查找作品图片
	   * @param worksId
	   * @return
	   */
	  public WorksImages findWorksImagesByWorksId(Integer worksId) {
	    WorksImages worksImages = null;
	    Connection conn = null;
	    PreparedStatement ps = null;
	    ResultSet rs = null;
	    String sql = "SELECT * FROM works,userinfo,works_images WHERE works.id=? "
	        + "AND works.userinfo_id=userinfo.id "
	        + "AND works_images.works_id = works.id";
	    try {
	      conn = DBHelper.getHelper().getConn();
	      ps = conn.prepareStatement(sql);
	      ps.setInt(1, worksId);
	      rs = ps.executeQuery();
	      
	      if (rs.next()) {
	        worksImages = new WorksImages();
	        Userinfo userinfo = new Userinfo();
	        userinfo.setId(rs.getInt("userinfo.id"));
	        userinfo.setName(rs.getString("userinfo.name"));
	        userinfo.setAvatar(rs.getString("userinfo.avatar"));
	        Works works = new Works();
	        works.setId(rs.getInt("works.id"));
	        works.setUserinfo(userinfo);
	        works.setTitle(rs.getString("works.title"));
	        works.setInfo(rs.getString("works.info"));
	        works.setInputTime(rs.getTimestamp("works.input_time"));
	        worksImages.setId(rs.getInt("works_images.id"));
	        worksImages.setWorks(works);
	        worksImages.setImageName(rs.getString("works_images.image_name"));
	      }
	    } catch (SQLException e) {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	    }
	    finally {
	      DBHelper.getHelper().closeConn(rs, ps, conn);
	    }
	    return worksImages;
	  }
	  
	  /**
	   *  上传作品图片
	   * @param imageName
	   */
	  public void upWorksImage(String imageName) {
	    String sql = "INSERT INTO works_images(works_id,image_name) SELECT MAX(id),? FROM works";
	    DBHelper.getHelper().executeUpdate(sql, imageName);
	  }

}
